﻿using UnityEngine;
using Utils.Events;
using Utils.Extends;

namespace Utils.Singleton
{
    public class CommonSingleton<T> where T : CommonSingleton<T>, new()
    {
        private static T _singleton;

        private static readonly object _lock = new object();
        private static bool _isInitialized;

        public static T Singleton
        {
            get
            {
                if (!_isInitialized)
                {
                    lock (_lock)
                    {
                        _singleton = new T();
                        _isInitialized = true;
                        _singleton.OnInitialize();
                        _singleton.UnregisterOnDestroy();
                    }
                }

                return _singleton;
            }
        }

        public static void Dispose()
        {
            lock (_lock)
            {
                if (_isInitialized)
                {
                    _singleton.OnDispose();
                    _singleton = null;
                    _isInitialized = false;
                }
            }
        }

        protected void UnregisterOnDestroy()
        {
            if (BindMono == null)
                return;
            DestroyEventHandler handler = BindMono.GetOrAddComponent<DestroyEventHandler>();
            handler.OnDestroyHandler += Dispose;
        }

        protected virtual MonoBehaviour BindMono => null;

        protected virtual void OnInitialize()
        {
        }

        protected virtual void OnDispose()
        {
        }
    }
}